import BaseForm, {
  BaseFormDight,
  BaseFormSelect,
  BaseFormTextArea,
  BaseModalForm,
  ProFormDateTimePicker,
  ProFormDependency,
  ProFormInstance,
  ProFormRadio
} from '@/components/base/BaseForm';
import { ModalFC } from '@/components/base/BaseModal';
import BaseTree from '@/components/base/BaseTree';
import { EnableStatusEnum } from '@/models';
import { RadarTreeTypeEnum } from '@/pages/radar/data';
import { getList as getRadarList, getRadarTreeListByRadarId } from '@/pages/radar/RadarInfo/api';
import { isEmpty } from '@/utils/is';
import { useRequest } from '@/utils/request';
import { BaseTimeEnum, formateDate } from '@/utils/time';
import { useMount } from 'ahooks';
import { Alert, Col, Row, Select, Spin } from 'antd';
import moment from 'moment';
import { useRef, useState } from 'react';
import { getList as getAMLList } from '../../AlgorithmModelLibraryInfo/api';
import { TaskModel } from '../../data';
import { getList as getTypeList } from '../../TaskTypeInfo/api';
import { addInfo, editInfo } from '../api';

const InfoModal: ModalFC<{ data?: TaskModel }> = (props) => {
  const { data = { cycle: 0 } as TaskModel, onSuccess, ...anyProps } = props;
  const { id, radarId, cycle, treeName = '' } = data;
  const isadd = isEmpty(id);
  const radarTree = useRequest(getRadarTreeListByRadarId, {
    manual: true
  });
  const [key, setKey] = useState(() => data.treeId ?? '');
  const date = formateDate(cycle);
  const [timeType, setTimeType] = useState(() => date.type);
  useMount(() => {
    if (radarId) {
      radarTree.run(radarId);
    }
  });
  const formRef = useRef<ProFormInstance<TaskModel>>();

  return (
    <BaseModalForm<TaskModel>
      formRef={formRef}
      title='任务信息'
      labelCol={{ style: { width: 80 } }}
      width={1200}
      initialValues={{ ...data, cycle: date.value }}
      {...anyProps}
      onFinish={async (values) => {
        values.id = id;
        values.treeId = key;
        values.cycle *= timeType;
        const { ok } = await (isadd ? addInfo : editInfo)(values);
        ok && onSuccess && onSuccess();
        return ok;
      }}
    >
      <Row gutter={16}>
        <Col span={10}>
          <BaseFormSelect
            label='任务雷达'
            name='radarId'
            request={getRadarList}
            fieldProps={{
              onChange: (v) => {
                if (v) {
                  radarTree.run(v);
                  setKey(v);
                }
              },
              fieldNames: { label: 'name', value: 'id' },
              defaultSelectedOptions: [{ name: treeName.split('-').shift(), id: data.radarId }]
            }}
            placeholder='请选择任务雷达'
            rules={[{ required: true, message: '请选择任务雷达' }]}
          />
          <Spin spinning={radarTree.loading}>
            {key === '' ? (
              <Alert type='warning' message='请先选择任务雷达' />
            ) : (
              <BaseForm.Item
                name='treeId'
                label='雷达结构'
                rules={[{ required: true, message: '请选择任务雷达结构' }]}
              >
                <BaseTree
                  blockNode
                  defaultExpandAll
                  treeData={radarTree.data}
                  bindProps={{ title: 'name', value: 'treeId', key: 'treeId' }}
                  height={320}
                  selectedKeys={[key]}
                  onSelect={([selectedKey], info) => {
                    setKey(selectedKey as string);
                    console.log(info);
                    const value = formRef.current?.getFieldsValue(true);
                    formRef.current?.setFieldsValue({ ...value, treeId: selectedKey });
                  }}
                  titleRender={(nodedata) => {
                    return (
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <span>{nodedata.title}</span>
                        <span>{RadarTreeTypeEnum.getLabelByValue(nodedata.type)}</span>
                      </div>
                    );
                  }}
                />
              </BaseForm.Item>
            )}
          </Spin>
        </Col>
        <Col span={14}>
          <Row gutter={12}>
            <Col span={12}>
              <BaseFormSelect
                label='任务类型'
                name='typeId'
                request={getTypeList}
                fieldProps={{
                  fieldNames: { label: 'name', value: 'id' },
                  defaultSelectedOptions: [{ name: data.typeName, id: data.typeId }]
                }}
                placeholder='请选择任务类型'
                rules={[{ required: true, message: '请选择任务类型' }]}
              />
            </Col>
            <Col span={12}>
              <ProFormDependency name={['typeId']}>
                {({ typeId }) => {
                  return (
                    <BaseFormSelect
                      label='算法模型'
                      name='algorithmModelId'
                      request={getAMLList}
                      fieldProps={{
                        params: { taskTypeId: typeId },
                        fieldNames: { label: 'cname', value: 'id' },
                        defaultSelectedOptions: [
                          { cname: data.algorithmModelCName, id: data.algorithmModelId }
                        ]
                      }}
                      placeholder='请选择任务算法模型'
                      rules={[{ required: true, message: '请选择任务算法模型' }]}
                    />
                  );
                }}
              </ProFormDependency>
            </Col>
            <Col span={12}>
              <ProFormDateTimePicker
                label='开始时间'
                name='startTime'
                fieldProps={{
                  format: 'yyyy-MM-DD HH:mm:ss',
                  style: { width: '100%' },
                  showTime: true,
                  disabledDate: (current) => {
                    return current && current < moment().startOf('day');
                  },
                  onChange() {
                    formRef.current?.validateFields(['endTime']);
                  }
                }}
                required
                rules={[
                  (form) => {
                    return {
                      validator: (_, value) => {
                        if (isEmpty(value)) {
                          return Promise.reject(new Error('请选择任务开始时间'));
                        }
                        const manu = form.getFieldValue('endTime');
                        if (
                          moment(value).format('YYYY-MM-DD') > moment(manu).format('YYYY-MM-DD')
                        ) {
                          return Promise.reject(new Error('开始时间不能在截止时间之后'));
                        }
                        return Promise.resolve();
                      }
                    };
                  }
                ]}
              />
            </Col>
            <Col span={12}>
              <ProFormDateTimePicker
                label='截止时间'
                fieldProps={{
                  format: 'yyyy-MM-DD HH:mm:ss',
                  style: { width: '100%' },
                  disabledDate: (current) => {
                    const addDate = formRef.current?.getFieldValue('startTime');
                    return (
                      current && current < (addDate ? moment(addDate) : moment().startOf('day'))
                    );
                  },
                  onChange() {
                    formRef.current?.validateFields(['startTime']);
                  }
                }}
                name='endTime'
                required
                rules={[
                  (form) => {
                    return {
                      validator: (_, value) => {
                        if (isEmpty(value)) {
                          return Promise.reject(new Error('请选择任务截止时间'));
                        }
                        const addDate = form.getFieldValue('startTime');

                        if (moment(value) < moment(addDate)) {
                          return Promise.reject(new Error('截止时间不能在开始时间之前'));
                        }
                        return Promise.resolve();
                      }
                    };
                  }
                ]}
              />
            </Col>
            <Col span={12}>
              <BaseFormDight
                label='任务周期'
                name='cycle'
                placeholder='请选择任务周期'
                required
                fieldProps={{ min: 0 }}
                rules={[{ required: true, message: '请选择任务周期' }]}
                addonAfter={
                  <Select
                    defaultValue={timeType}
                    onChange={(v) => {
                      setTimeType(v);
                    }}
                    options={BaseTimeEnum.list}
                  />
                }
              />
            </Col>
            <Col span={12}>
              <ProFormRadio.Group
                label='启用状态'
                name='status'
                radioType='button'
                options={EnableStatusEnum.list}
                rules={[{ required: true, message: '请选择任务状态' }]}
              />
            </Col>
            <Col span={24}>
              <BaseFormTextArea
                label='任务描述'
                name='remarks'
                placeholder='请输入任务描述'
                rules={[{ required: true, message: '请输入任务描述' }]}
              />
            </Col>
          </Row>
        </Col>
      </Row>
    </BaseModalForm>
  );
};

export default InfoModal;
